package net.lookyou.boot.demo.web;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.google.zxing.WriterException;
import com.google.zxing.qrcode.QRCodeWriter;
import lombok.extern.slf4j.Slf4j;
import net.lookyou.boot.demo.config.redis.RedisSessionService;
import net.lookyou.boot.demo.entity.SysUser;
import net.lookyou.boot.demo.utils.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

@Slf4j
@Controller
@RequestMapping("/commons")
public class CommonsController extends  BaseController{

    @Resource
    HttpSession session;

    @Autowired
    SessionRegistry sessionRegistry;

    @Resource
    RedisSessionService redisSessionService;

    @Resource
    HttpServletResponse response;

    @Resource
    RedisUtil redisUtil;

    @Value("${basePath}")
    private String basePath;

    @GetMapping("/test")
    public void test(String key){
        System.out.println("====================="+redisUtil.get(key));
    }

    @GetMapping("/code")
    void getCode() throws IOException {
        // 利用 hutool 工具，生成验证码图片资源
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 5);
        // 获得生成的验证码字符
        String code = captcha.getCode();
        // 利用 session 来存储验证码
        session.setAttribute("code",code);
        // 将验证码图片的二进制数据写入【响应体 response 】
        captcha.write(response.getOutputStream());
    }

    /**
     * 踢人下线
     * @param account
     */
    @GetMapping("/kick")
    public void kickPeople(String account){
        redisSessionService.destroySession(account);
    }

    @RequestMapping("/QRCimg")
    public void getQRCimg(HttpServletRequest request, HttpServletResponse response, String phone) throws WriterException, IOException {

        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        if(StringUtils.isBlank(phone)){
            phone = "13414485481";
        }

        String uuid = UUID.randomUUID().toString();
        String text = basePath.concat("QRCLogin?uuid="+uuid+"&phone="+phone);
        /*// 生成二维码并指定宽高
        BufferedImage generate = QrCodeUtil.generate(text, 300, 300);

        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(generate, "png", os);
        } catch (IOException e) {
            return e.getMessage();
        }
        //如果二维码要在前端显示需要转成Base64
        String base64 = "data:image/png;base64,";
        String encode = Base64.getEncoder().encodeToString(os.toByteArray());*/

        //return base64 + encode;
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        File logoFile = FileUtil.file(this.getClass().getResource("/static/img/logo.jpg").getFile());
        QrConfig qrConfig = QrConfig.create().setImg(logoFile);
        qrConfig.setWidth(300);
        qrConfig.setHeight(300);

        // 生成指定url对应的二维码到文件，宽和高都是300像素
        QrCodeUtil.generate(text, qrConfig, "jpg", response.getOutputStream());
        //QrCodeUtil.generate(text, 300, 300, "jpg", response.getOutputStream());
        session.setAttribute("path",text);
        session.setAttribute(uuid,null);
    }

    /**
     * 模拟扫码登录
     * @param uuid
     * @param phone
     */
    @RequestMapping("/QRCLogin/{uuid}/{phone}")
    public boolean scanCode(@PathVariable String uuid, @PathVariable String phone){
        if(StringUtils.isNotBlank(uuid) && StringUtils.isNotBlank(phone)){
            session.setAttribute(uuid, phone);
            return true;
        }
        return false;
    }

    /**
     * 检查是否扫码成功
     * @param uuid
     * @return
     */
    @RequestMapping("/checkQRC/{uuid}")
    public String checkLogin(@PathVariable String uuid){
        String result = "";
        if(StringUtils.isNotBlank(uuid)){
            Object value = session.getAttribute(uuid);
            if(Objects.nonNull(value)){
                result = value.toString();
            }
        }
        return result;
    }


    /**
     * 验证session是否共享了
     * @return
     */
    @RequestMapping("/checkSession")
    public String checkSession(){
        return (String)session.getAttribute("code");
    }

    @RequestMapping("/userOnLine")
    public List<SysUser> getAllOnlineUser() {
        List<Object> list = sessionRegistry.getAllPrincipals();
        log.info("在线人数=[{}]", list.size());
        List<SysUser> userList = new ArrayList<>();
        for (Object o : list) {
            if (o instanceof SysUser) {
                SysUser user = (SysUser) o;
                userList.add(user);
            }
        }
        return userList;
    }
}
